extends Camera2D

var targetPosition = Vector2.ZERO
var sourcePosition
export(Color, RGB) var backgroundColor
export(OpenSimplexNoise) var shakeNoise

var xNoiseSampleVector = Vector2.RIGHT	# 获取样本的方向
var yNoiseSampleVector = Vector2.DOWN
var xNoiseSamplePosition = Vector2.ZERO
var yNoiseSamplePosition = Vector2.ZERO

var noiseSampleTravelRate = 500	# 当前抖动的delta速率
export var maxShakeOffset = 6 # 当前抖动的最大偏移量
var currentShakePercentage = 0	# 当前抖动百分比
export var shakeDecay = 4	# 抖动衰减

func _ready():
	VisualServer.set_default_clear_color(backgroundColor)
	apply_shake(1)	# 初始化currentShakePercentage为一个正常的随机百分比

func _process(delta):
	acquire_target_position()	# 获取玩家的目标位置
	global_position = lerp(targetPosition, global_position, pow(2, -15 * delta))	# 将相机平滑地移动到玩家的位置上
	# ------------------- 相机抖动效果 -------------------
	if (currentShakePercentage > 0):	# 如果当前的抖动百分比大于零(正常来说一定是大于零的)
		xNoiseSamplePosition += xNoiseSampleVector * noiseSampleTravelRate * delta
		yNoiseSamplePosition += yNoiseSampleVector * noiseSampleTravelRate * delta
		# 获取x方向上的噪声位置和y上的噪声位置	（都是平面向量） = 对应方向的单位向量乘上抖动的速度*delta
		var xSample = shakeNoise.get_noise_2d(xNoiseSamplePosition.x, xNoiseSamplePosition.y)
		var ySample = shakeNoise.get_noise_2d(yNoiseSamplePosition.x, yNoiseSamplePosition.y)
		# 获取噪声位置的采样值
		var calculatedOffset = Vector2(xSample, ySample) * maxShakeOffset * pow(currentShakePercentage, 2)
		# 根据噪声采样值来进行偏移实现抖动效果
		# 用乘上抖动百分比来削减当前的相机偏移量
		offset = calculatedOffset
		currentShakePercentage = clamp(currentShakePercentage - shakeDecay * delta, 0, 1)
		# 不断削弱抖动直至相机停止运动
	# ---------------------------------------------------------

func apply_shake(percentage):
	currentShakePercentage = clamp(currentShakePercentage + percentage, 0, 1)
	# 将当前的抖动百分比+1，但是限制在(0, 1)的范围内
	# 本质上其实就是生成了一个(1% ~ 100%)范围内的正常百分比而已

func acquire_target_position():
	var acquire = get_target_position_from_node_group("player")
	if (!acquire):
		get_target_position_from_node_group("player_death")
		
# 判断目标组中是否有孩子并且寻找。
func get_target_position_from_node_group(groupName):
	var target_group = get_tree().get_nodes_in_group(groupName)
	if target_group.size() > 0:
		var target = target_group[0]
		targetPosition = target.global_position
		# 如果能找到玩家返回设置相机的跟随位置 true，否则返回 false
		return true
	return false
